package demo;

import java.io.*;
import java.util.Scanner;



public class demo3 {

    public static void main(String[] args) {
        //1.输入
        Scanner in = new Scanner(System.in);
        System.out.println("输入要查询的文件路径:");
        String s1 = in.next();
        System.out.println("请输入要查询的文件内容关键字：");//包括文件的名字:也就是一个文件的绝对路径
        String s2 = in.next();
        //2.检查合法性
        File file1 = new File(s1);
        if(!file1.isDirectory()) {
            System.out.println("查询目录非法");
            return;
        }
        //3.递归查询
        findFile(file1,s2);
    }

    private static void findFile(File file1, String s2) {
        File[] files = file1.listFiles();
        if(files == null) {
            return;
        }
        for(File f : files) {
            if(f.isFile()) {
                find(f,s2);
            }else if(f.isDirectory()) {
                findFile(f,s2);
            }
        }
    }

    private static void find(File f, String s2) {
        try(InputStream inputStream = new FileInputStream(f)) {
            //StringBuilder s = new StringBuilder();//将文件的内容全部拼接在一个字符串上面
            String s = new String();
            while (true) {
                int n = inputStream.read();
                if(n==-1) break;
                s+=(char)n;
            }
            if(s.indexOf(s2)>=0) {
                System.out.println("找到了："+f.getAbsolutePath());
            }
        }catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
